package com.penghaisoft.microwms.material.web.insidewarehouse.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.dto.RawStorageDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.RawContractChange;
import com.penghaisoft.microwms.common.wms.model.RawCountingDifference;
import com.penghaisoft.microwms.common.wms.model.RawCountingRecords;
import com.penghaisoft.microwms.common.wms.model.RawCountingTask;
import com.penghaisoft.microwms.common.wms.model.RawLockLog;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawContractChangeMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawCountingDifferenceMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawCountingRecordsMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawCountingTaskMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawLockLogMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.dao.RawStorageSnMapper;
import com.penghaisoft.microwms.material.web.insidewarehouse.service.IMaterialInsideService;

@Slf4j
@Service("materialInsideService")
public class MaterialInsideServiceImpl extends BaseService implements
		IMaterialInsideService {

	@Autowired
	private RawStorageSnMapper rawStorageSnMapper;
	@Autowired
	private RawLockLogMapper rawLockLogMapper;
	@Autowired
	private RawCountingTaskMapper rawCountingTaskMapper;
	@Autowired
	private RawCountingRecordsMapper rawCountingRecordsMapper;
	@Autowired
	private RawCountingDifferenceMapper rawCountingDifferenceMapper;
	@Autowired
	private RawContractChangeMapper rawContractChangeMapper;

	/*
	 * @Title: findListByCondition
	 * 
	 * @Description: TODO
	 * 
	 * @author jzh
	 * 
	 * @date 2018年5月10日 下午5:36:54
	 */
	@Override
	public Pager<RawStorageDto> findListByCondition(int page, int rows,
			RawStorageDto condition) {
		Pager<RawStorageDto> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);

		long size = rawStorageSnMapper.queryRawStorageDtoCount(condition);
		List<RawStorageDto> records = new ArrayList<RawStorageDto>();
		if (size > 0) {
			records = rawStorageSnMapper.queryStorageDtoList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	/* @Title: queryStorageDtoList 
	 * @Description: 查询库存数据
	 * @author luoteng
	 * @date 2018年8月14日 上午11:51:02 
	 */
	@Override
	public List<RawStorageDto> queryStorageDtoList(RawStorageDto condition){
		return rawStorageSnMapper.queryStorageDtoList(null, condition);
	}

	/*
	 * @Title: findRawStorageSnByCondition
	 * 
	 * @Description: TODO
	 * 
	 * @author jzh
	 * 
	 * @date 2018年5月18日 上午11:14:08
	 */
	@Override
	public Pager<RawStorageSn> findRawStorageSnByCondition(int page, int rows,
			RawStorageSn condition) {
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = rawStorageSnMapper.queryCount(condition);
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		if (size > 0) {
			records = rawStorageSnMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	@Override
	public List<RawStorageSn> findRawStorageSnByCode(RawStorageSn rawStorageSn) {

		return rawStorageSnMapper.queryRawStorageSnByCode(rawStorageSn);
	}

	/*
	 * @Title: updateRawStorageSnStatus
	 * 
	 * @Description: 冻结解冻条码
	 * 
	 * @author jzh
	 * 
	 * @date 2018年5月22日 上午11:24:53
	 */
	@Override
	@Transactional
	public Resp updateRawStorageSnStatus(List<RawStorageSn> list,
			RawLockLog rawLockLog) {
		RawStorageSn rawStorageSn = new RawStorageSn();
		List<Integer> rawStorageSnIdList = new ArrayList<Integer>();
		String currentUserName = rawLockLog.getLockBy();
		Date date = new Date();
		for (RawStorageSn tmp : list) {
			rawStorageSnIdList.add(tmp.getStorageSnId());

			RawStorageSn cond = new RawStorageSn();
			cond.setStorageSnId(tmp.getStorageSnId());
			// 根据snid（唯一）查询，实际一条sn数据
			List<RawStorageSn> RawStorageSnlist = rawStorageSnMapper
					.queryRawStorageSnByCode(cond);
			if (RawStorageSnlist.size() > 0) {
				// 冻结解冻日志记录
				RawLockLog lockLog = new RawLockLog();
				lockLog.setBarcode(RawStorageSnlist.get(0).getBarcode());
				lockLog.setModel(RawStorageSnlist.get(0).getModel());
				lockLog.setModelDesc(RawStorageSnlist.get(0).getModelDesc());
				lockLog.setWlCode(RawStorageSnlist.get(0).getWlCode());
				lockLog.setLockReason(tmp.getLockReason());
				lockLog.setLockBy(currentUserName);
				lockLog.setLockDate(date);
				lockLog.setLockType(tmp.getBarcodeStatus());
				lockLog.setGmtCreate(date);
				lockLog.setCreateBy(currentUserName);
				lockLog.setActiveFlag("1");
				rawLockLogMapper.create(lockLog);
			}

		}
		// rawStorageSnIdList条码集合（一次更新）
		rawStorageSn.setRawStorageSnIdList(rawStorageSnIdList);
		rawStorageSn.setLockReason(list.get(0).getLockReason());
		rawStorageSn.setLastModifiedBy(currentUserName);
		rawStorageSn.setGmtModified(date);
		String status = list.get(0).getBarcodeStatus();
		rawStorageSn.setBarcodeStatus(status);
		// 冻结解冻更新状态
		Integer updateCnt = rawStorageSnMapper.updateOpenClose(rawStorageSn);
		System.out.println("更改数量：" + updateCnt);
		if (updateCnt.intValue() <= 0) {
			throw new RuntimeException("更改条码失败");
		}
		int modiNum = rawStorageSn.getRawStorageSnIdList().size();
		if (updateCnt.intValue() != modiNum) {
			throw new RuntimeException("更新条码的数量和修改条码的数量不一致！");
		}
		return success();
	}

	@Override
	public Pager<RawLockLog> findLockLogByCondition(int page, int rows,
			RawLockLog rawLockLog) {
		Pager<RawLockLog> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		rawLockLog.preQuery();
		long size = rawLockLogMapper.queryCount(rawLockLog);
		List<RawLockLog> records = new ArrayList<RawLockLog>();
		if (size > 0) {
			records = rawLockLogMapper.queryList(pager, rawLockLog);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	@Override
	public Pager<RawCountingTask> findCountingTask(int page, int rows,
			RawCountingTask rawCountingTask) {
		Pager<RawCountingTask> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		rawCountingTask.preQuery();
		long size = rawCountingTaskMapper.queryCount(rawCountingTask);
		List<RawCountingTask> records = new ArrayList<RawCountingTask>();
		if (size > 0) {
			records = rawCountingTaskMapper.queryList(pager, rawCountingTask);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	@Override
	public Resp createCountingTask(RawCountingTask rawCountingTask) {
		rawCountingTaskMapper.create(rawCountingTask);
		return success();
	}

	@Override
	public Resp deleteCountingTask(RawCountingTask rawCountingTask) {
		rawCountingTaskMapper.delete(rawCountingTask);
		return success();
	}

	@Override
	public List<RawCountingRecords> findRawCountingRecordsByCode(
			RawCountingRecords rawCountingRecords) {

		return rawCountingRecordsMapper
				.queryRawCountingRecordsByCode(rawCountingRecords);
	}

	@Override
	public Pager<RawCountingDifference> findRawCountingDifferenceByCondition(
			int page, int rows, RawCountingDifference rawCountingDifference) {
		Pager<RawCountingDifference> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		rawCountingDifference.preQuery();
		long size = rawCountingDifferenceMapper
				.queryCount(rawCountingDifference);
		List<RawCountingDifference> records = new ArrayList<RawCountingDifference>();
		if (size > 0) {
			records = rawCountingDifferenceMapper.queryList(pager,
					rawCountingDifference);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;

	}

	/**
	 * @Title createRawStorageSn
	 * @Description 库存明细新增【黑白料出库】
	 * @author luoteng
	 * @date 2018年6月4日:下午1:41:26
	 * @param rawStorageSn
	 * @return int
	 */
	@Override
	public Resp createRawStorageSnOut(RawStorageSn rawStorageSn) {
		Resp resp = new Resp();
		
		RawStorageDto rawStorageDto = new RawStorageDto();
		rawStorageDto.setModel(rawStorageSn.getModel());
		rawStorageDto.setModelType(rawStorageSn.getModelType());
		List<RawStorageDto> records = rawStorageSnMapper.queryStorageDtoList(null, rawStorageDto);
		if(records == null || records.isEmpty()){
			resp.setCode(Constant.FAIL);
			resp.setMsg("该原材料型号没有库存！");
			return resp;
		}else{
			RawStorageDto compare = records.get(0);
			if(rawStorageSn.getAmount().negate().compareTo(compare.getAvailAmount()) > 0){
				resp.setCode(Constant.FAIL);
				resp.setMsg("该原材料型号库存不足！");
				return resp;
			}
			rawStorageSnMapper.create(rawStorageSn);
		}
		
		return success();
	}
	
	/**
	 * @Title createRawStorageSn
	 * @Description 库存明细新增【黑白料入库】
	 * @author luoteng
	 * @date 2018年6月4日:下午1:41:26
	 * @param rawStorageSn
	 * @return int
	 */
	@Override
	public Resp createRawStorageSnIn(RawStorageSn rawStorageSn) {
		rawStorageSnMapper.create(rawStorageSn);
		return success();
	}

	/**
	 * @Title updateRawStorageSn
	 * @Description 库存明细修改
	 * @author luoteng
	 * @date 2018年6月4日:下午1:42:15
	 * @param rawStorageSn
	 * @return int
	 */
	@Override
	public int updateRawStorageSn(RawStorageSn rawStorageSn) {
		return rawStorageSnMapper.updateBySelect(rawStorageSn);
	}
	
	/** 
	 * @Title updateRawStorageSnOut
	 * @Description 库存明细修改【黑白料出库】
	 * @author luoteng
	 * @date 2018年7月13日:上午11:05:41
	 * @param rawStorageSn
	 * @return Resp
	 */
	@Override
	public Resp updateRawStorageSnOut(RawStorageSn rawStorageSn) {
		Resp resp = new Resp();
		
		RawStorageSn tmp = rawStorageSnMapper.queryById(rawStorageSn.getStorageSnId().toString());
		
		RawStorageDto rawStorageDto = new RawStorageDto();
		rawStorageDto.setModel(rawStorageSn.getModel());
		rawStorageDto.setModelType(rawStorageSn.getModelType());
		List<RawStorageDto> records = rawStorageSnMapper.queryStorageDtoList(null, rawStorageDto);
		if(records == null || records.isEmpty()){
			resp.setCode(Constant.FAIL);
			resp.setMsg("该原材料型号没有库存！");
			return resp;
		}else{
			RawStorageDto compare = records.get(0);
			BigDecimal nowAddAmount = rawStorageSn.getAmount().negate().subtract(tmp.getAmount().negate());
			if(nowAddAmount.compareTo(BigDecimal.ZERO) > 0){
				if(nowAddAmount.compareTo(compare.getAvailAmount()) > 0){
					resp.setCode(Constant.FAIL);
					resp.setMsg("该原材料型号库存不足！");
					return resp;
				}
			}
			
			rawStorageSnMapper.updateBySelect(rawStorageSn);
		}
		return success();
	}

	/**
	 * @Title findRawStorageSnWhiteBlackIn
	 * @Description 黑白料入库明细
	 * @author luoteng
	 * @date 2018年6月4日:下午4:41:03
	 * @param page
	 * @param rows
	 * @param rawStorageSn
	 * @return Pager<RawStorageSn>
	 */
	@Override
	public Pager<RawStorageSn> findRawStorageSnWhiteBlackIn(int page, int rows,
			RawStorageSn rawStorageSn) {
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		rawStorageSn.preQuery();
		
		List<String> modelTypeList = new ArrayList<String>();
		modelTypeList.add(Constant.MODEL_B);
		modelTypeList.add(Constant.MODEL_H);
		rawStorageSn.setModelTypeList(modelTypeList);
		
		long size = rawStorageSnMapper.queryCountWhiteBlackIn(rawStorageSn);
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		if (size > 0) {
			records = rawStorageSnMapper.queryListWhiteBlackIn(pager, rawStorageSn);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	/** 
	 * @Title findRawStorageSnWhiteBlackOut
	 * @Description 黑白料出库明细
	 * @author luoteng
	 * @date 2018年6月4日:下午4:41:14
	 * @param page
	 * @param rows
	 * @param rawStorageSn
	 * @return Pager<RawStorageSn>
	 */
	@Override
	public Pager<RawStorageSn> findRawStorageSnWhiteBlackOut(int page, int rows, RawStorageSn rawStorageSn){
		Pager<RawStorageSn> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		rawStorageSn.preQuery();
		
		List<String> modelTypeList = new ArrayList<String>();
		modelTypeList.add(Constant.MODEL_B);
		modelTypeList.add(Constant.MODEL_H);
		rawStorageSn.setModelTypeList(modelTypeList);
		
		long size = rawStorageSnMapper.queryCountWhiteBlackOut(rawStorageSn);
		List<RawStorageSn> records = new ArrayList<RawStorageSn>();
		if (size > 0) {
			records = rawStorageSnMapper.queryListWhiteBlackOut(pager, rawStorageSn);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
	
	/** 
	 * @Title findRawStorageSnAbs
	 * @Description 查询库存明细列表（数量取绝对值）
	 * @author luoteng
	 * @date 2018年6月4日:下午5:28:41
	 * @param rawStorageSn
	 * @return List<RawStorageSn>
	 */
	@Override
	public List<RawStorageSn> findRawStorageSnAbs(RawStorageSn rawStorageSn){
		return rawStorageSnMapper.queryByAnyAbs(rawStorageSn);
	}

	/**
	 * 根据id查询条码的合同号（只查合同号）
	 * @wzhg 1865
	 * @param rawStorageSn
	 * @return
	 */
	@Override
	public RawStorageSn findById(RawStorageSn rawStorageSn) {
		return rawStorageSnMapper.findById(rawStorageSn);
	}

	/**
	 * 根据id修改合同号(可以置为空可以修改为其他值)
	 * @wzhg 1865
	 * @update jzh
	 * @return
	 */
	@Override
	@Transactional
	public Resp updateById(RawStorageSn rawStorageSn) {
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		//查出信息
		RawStorageSn tmp = new RawStorageSn();
		tmp.setStorageSnId(rawStorageSn.getStorageSnId());
		List<RawStorageSn> list = rawStorageSnMapper.queryByAny(tmp);
		if(list.size() <= 0){
			resp.setCode(Constant.FAIL);
			resp.setMsg("查询不到条码");
			return resp;
		}
		rawStorageSnMapper.updateById(rawStorageSn);
		//记录合同号修改日志
		if(list.size()>0){
			RawContractChange contractChange = new RawContractChange();
			contractChange.setBarcode(list.get(0).getBarcode());
			contractChange.setAmount(list.get(0).getAmount());
			contractChange.setUnit(list.get(0).getUnit());
			contractChange.setContractNoOld(list.get(0).getContractNo());
			contractChange.setContractNoNew(rawStorageSn.getContractNo());
			contractChange.setModel(list.get(0).getModel());
			contractChange.setModelDesc(list.get(0).getModelDesc());
			contractChange.setModelType(list.get(0).getModelType());
			contractChange.setWlCode(list.get(0).getWlCode());
			contractChange.setCreateBy(rawStorageSn.getLastModifiedBy());
			contractChange.setGmtCreate(rawStorageSn.getGmtModified());
			contractChange.setActiveFlag("1");
			rawContractChangeMapper.create(contractChange);
		}
		
		return resp;
	}
	
	@Override
	public Resp updateBySelect(RawStorageSn rawStorageSn) {
		Resp resp = new Resp();
		rawStorageSnMapper.updateBySelect(rawStorageSn);
		return success();
	}

	/**
	 * @wzhg 1865
	 * 根据条码号查询条码信息 用list.get(0) /方便查错
	 * @param rawStorageSn
	 * @return
	 */
	@Override
	public List<RawStorageSn> findByCode(RawStorageSn rawStorageSn) {
		return rawStorageSnMapper.findByCode(rawStorageSn);
	}
	
	
	@Override
	public List<RawStorageDto> queryAvailAmountList(RawStorageDto condition) {
		return rawStorageSnMapper.queryAvailAmountList(condition);
	}
	
	/** 
	* @Title: batchUpdateContact 
	* @Description: 批量更新合同号
	* @param @param rawStorageSn
	* @param @return  参数说明 
	* @return Resp    返回类型
	* @author luoteng 
	* @date 2018年8月14日 上午10:08:21 
	* @throws 
	*/
	@Override
	@Transactional
	public Resp batchUpdateContact(RawStorageSn rawStorageSn){
		Resp resp = new Resp();
		resp.setCode(Constant.SUCCESS);
		RawStorageSn tmp = new RawStorageSn();
		tmp.setContractNo(rawStorageSn.getContractNoOld());
		tmp.setModel(rawStorageSn.getModel());
		tmp.setModelType(rawStorageSn.getModelType());
		tmp.setWlCode(rawStorageSn.getWlCode());
//		0可用；1 冻结；2已出库 3 报废
		tmp.setBarcodeStatus("0");
		tmp.setActiveFlag("1");
		List<RawStorageSn> list = rawStorageSnMapper.queryByAny(tmp);
		if(list != null && !list.isEmpty()){
			int modiAmount = rawStorageSn.getModiAmount() != null ? rawStorageSn.getModiAmount().intValue() : 0;
			if(modiAmount > list.size()){
				resp.setCode(Constant.FAIL);
				resp.setMsg("该合同下可用条码小于" + modiAmount + "个！");
				return resp;
			}
			List<Integer> ids = new ArrayList<Integer>();
			for(int i = 0; i < modiAmount; i++){
				ids.add(list.get(i).getStorageSnId());
			}
			
			RawStorageSn upOb = new RawStorageSn();
			upOb.setContractNo(rawStorageSn.getContractNo());
			upOb.setStorageSnIdList(ids);
			Integer upAmount = rawStorageSnMapper.updateBySelectIds(upOb);
			if(modiAmount > upAmount){
				throw new RuntimeException("该合同内本次待修改条码状态发生改变，请再次尝试！");
			}
			//创建合同修改记录
			Date now = new Date();
			RawContractChange contractChange = null;
			for(int i = 0; i < modiAmount; i++){
				contractChange = new RawContractChange();
				contractChange.setBarcode(list.get(i).getBarcode());
				contractChange.setAmount(list.get(i).getAmount());
				contractChange.setUnit(list.get(i).getUnit());
				contractChange.setContractNoOld(rawStorageSn.getContractNoOld());
				contractChange.setContractNoNew(rawStorageSn.getContractNo());
				contractChange.setModel(list.get(i).getModel());
				contractChange.setModelDesc(list.get(i).getModelDesc());
				contractChange.setModelType(list.get(i).getModelType());
				contractChange.setWlCode(list.get(i).getWlCode());
				//controller中的登陆人暂存在LastModifiedBy
				contractChange.setCreateBy(rawStorageSn.getLastModifiedBy());
				contractChange.setGmtCreate(now);
				contractChange.setActiveFlag("1");
				rawContractChangeMapper.create(contractChange);
				
			}
		}
		return resp;
	}
	/**
	* @Description: 合同号修改记录查询
	* @param @param rawContractChange
	* @author lengxf 
	* @date 2018年8月14日 上午10:08:21 
	*/
	@Override
	public Pager<RawContractChange> findRawContractChange(int page, int rows, RawContractChange rawContractChange) {
		Pager<RawContractChange> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);

		long size = rawContractChangeMapper.queryCount(rawContractChange);
		List<RawContractChange> records = new ArrayList<RawContractChange>();
		if (size > 0) {
			records = rawContractChangeMapper.queryList(pager, rawContractChange);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
}
